<?php
/**
 * 获取并解析广告报表
 * Date: 2023/12/22
 * Time: 17:56
 */

namespace App\Console\Commands\AdsApi;


use App\Logic\Amazon\AdsApi\ReportRequest;
use App\Models\AmazonAds\AdsDailyReport;
use Illuminate\Console\Command;
use JetBrains\PhpStorm\NoReturn;

class GetParseAdsReport extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ads:get-parse-report {startDate=null} {endDate=null} {accountId=0}';

    /**
     * The console command description.
     * @var string
     */
    protected $description = 'exe func';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle(){

        $startDate = $this->argument('startDate');
        $endDate = $this->argument('endDate');
        $accountId = $this->argument('accountId');

        //日期 (默认日期：昨天)
        $startDates = $startDate == 'null' ? date('Y-m-d', strtotime("-2 days")) : $startDate;
        $endDates = $endDate == 'null' ? date('Y-m-d', strtotime("-2 days")) : $endDate;
        if (!strtotime($startDates) || !strtotime($endDates)) return false;

        $bof = strtotime($startDates); //开始
        $eof = strtotime($endDates); //结束
        $i = 1;
        while(true) {
            if ($bof > $eof) break;
            $time = $bof;
            $date = date('Y-m-d', $time);

            $query = AdsDailyReport::query();
            if ($accountId > 0) {
                $query->where('account_id', $accountId);
            }
            $query->where('start_date', $date);
            $query->where('end_date', $date);
            $query->where('create_report_status', '<=', AdsDailyReport::STATUS_COMPLETED); //尚未创建完成的 (取值范围：[1待处理,2处理中])
            $query->where('download_parse_status', '<>', AdsDailyReport::PARSE_YES); //尚未解析和解析异常的 (取值范围：[0未解析,2解析异常])
            $query->chunk(500, function ($models) use($i,$date){
                foreach ($models as $model){
                    //获取and解析广告数据
                    echo '--------Start：'.$model->id.'-'.$model->account_id.'-('.$date.')-'.$i.'--------'.PHP_EOL;
                    ReportRequest::getReport($model);

                    $i++;
                    sleep(2);
                }
            });

            echo 'over:'.$date.PHP_EOL;
            $bof += 86400; //+1天
        }
        $this->info('finish!');
    }

}
